﻿using System.Threading.Tasks;
using System.Web.Mvc;

using NJ.Common.Extension;
using NJ.Common.Tools.Images;
using NJ.Common.Web;
using NJ.Dto.User;
using NJ.Service.User;
using NJ.Web.Filter;
using NJ.Web.Models;

namespace NJ.Web.Controllers
{
    [AllowAnonymous]
    public class AccountController : Controller
    {
        private IUserService userService;
        public AccountController(IUserService _userService)
        {
            userService = _userService;
        }
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        [LoginMonitoring]
        public async Task<ActionResult> Login(string username, string password, string checkcode)
        {
            ViewData["UserName"] = username;
            var tempCode = TempData["checkcode"]?.ToString();
            if (tempCode == null)
            {
                return Json(new HttpResult { status = ResultState.fail, msg = "验证码过期，请刷新！" });
            }
            else if (tempCode.ToLower() != checkcode.ToLower())
            {
                return Json(new HttpResult { status = ResultState.fail, msg = "验证码错误！" });
            }
            else
            {
                password = password.ToMd5().ToUpper();
                UserDto user = await userService.GetUserAsync(username: username);
                if (user == null)
                {
                    return Json(new HttpResult { status = ResultState.fail, msg = "用户名不存在！" });
                }
                else
                {
                    user = await userService.GetUserAsync(username, password);
                    if (user == null)
                    {
                        return Json(new HttpResult { status = ResultState.fail, msg = "密码错误！" });
                    }
                    else
                    {
                        CurUser.Set(user);
                        return Json(new HttpResult { status = ResultState.success, msg = "成功" });
                    }
                }
            }

        }
        public ActionResult Logout()
        {
            CurUser.Clear();
            return RedirectToAction("Login");
        }
        public ActionResult GetCheckCode()
        {
            VerificationCode vh = new VerificationCode();
            string code = vh.GetRandomNumberString(4);
            TempData["checkcode"] = code;
            byte[] img = vh.CreateImage(code);
            return File(img, "image/jpeg");
        }
    }
}